import Loading from './loading';
import Vue from 'vue';

const LoadingConstructor = Vue.extend(Loading);

var instances = [];

var instance = null;
var showed = false;
var disalbe = false;

const generate = function({ content = '' }) {
  const vm = new LoadingConstructor({
    propsData: {
      value: true,
      content
    }
  }).$mount();
  showed = true;
  vm.$on('input', val => {
    if (!val) {
      vm.value = false;
      showed = false;
    }
  });
  vm.$on('hide', () => {
    showed = false;
    vm.$destroy();
  });
  return vm;
};
Loading.show = (content = '加载中') => {
  if (disalbe) {
    return;
  }
  let index = instances.length + 1;
  instances.push(index);
  if (!showed) {
    instance = generate({ content });
  }
};
Loading.hide = () => {
  if (instances.length > 0) {
    instances.pop();
    if (instances.length <= 0) {
      if (instance) {
        instance.close();
      }
    }
  }
};
Loading.closeAll = () => {
  instances = [];
  instance.close();
};
Loading.disable = () => {
  console.log('禁用Loading');
  disalbe = true;
};
Loading.enable = () => {
  console.log('启用Loading');
  disalbe = false;
};
export default Loading;
